<template>
  <div class="fileList">
    <div class="oneFile" v-for="(data, index) in formData[formData.valueName]">
      <div class="oneFileBody">
        <el-icon size="20px"><Document /></el-icon>
        <div class="fileName" :title="data">{{ data.name }}</div>
        <el-icon size="16px" class="download" @click="download(data.url, data.name)"><Download /></el-icon>
        <el-icon size="16px" class="delBtn" @click="deleteOne(data, index)"  v-if="formStatus === 'edit'"><CircleCloseFilled /></el-icon>
      </div>
    </div>
  </div>
  <div v-if="formStatus === 'edit'">
    <el-upload
        :action="formData.uploadUrL"
        v-model:file-list="files"
        :limit="formData.multiple ? formData.limit : null"
        :on-success="handleUploadSuccess"
        :before-upload="handleBefore"
        :on-exceed="handleExceed"
        :show-file-list="false"
        :headers="headers"
        :multiple="formData.multiple"
        class="upload-file-uploader"
        ref="upload"
    >
      <!-- 上传按钮 -->
      <el-button type="primary">选取文件</el-button>
    </el-upload>
  </div>
</template>

<script setup name="uploadBox">
import {reactive, ref, watch} from "vue";
import {ElMessage, genFileId} from "element-plus";

const headers = ref({ Authorization: 'Bearer '})
const options = ref([])
const files = ref([])
const num = ref(0)
const upload = ref(null)
const props = defineProps({
  formData: {
    type: Object,
    default: () => {},
    required: true
  },
  formStatus: {
    type: String,
    default: 'edit'
  }
})

function deleteOne(data , index) {
  props.formData[props.formData.valueName].splice(index, 1)
}

function handleBefore() {
  num.value = props.formData[props.formData.valueName].length
  const fileLength = num.value + files.value.length
  if ( fileLength > props.formData.limit) {
    files.value = []
    ElMessage({
      message: `超出限制了，你已选择了${props.formData[props.formData.valueName].length}个文件，你最多只能选择${props.formData.limit}个`,
      type: 'warning',
    })
    return false
  }
}

function handleUploadSuccess(response,uploadFile, uploadFiles) {
  if (!props.formData.multiple) {
    props.formData[props.formData.valueName] = []
  }
  props.formData[props.formData.valueName].push({
    name: response.data.name,
    url: response.data.url
  })
  const aLength  = props.formData[props.formData.valueName].length - num.value
  if ( aLength === uploadFiles.length ) {
    console.log('上传完了')
    files.value = []
    upload.value.clearFiles()
  }

}

function handleExceed (files, fileList) {
  ElMessage({
    message: `超出限制了，你最多只能选择${props.formData.limit}个`,
    type: 'warning',
  })
  upload.value.clearFiles()
  return false
}

function getBlob(url,cb) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  xhr.onload = function() {
    if (xhr.status === 200) {
      cb(xhr.response);
    }
  };
  xhr.send();
}

function download(url, filename) {
  getBlob(url, function(blob) {
    saveAs(blob, filename);
  })
}

function saveAs(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    const link = document.createElement('a');
    const body = document.querySelector('body');

    link.href = window.URL.createObjectURL(blob);
    link.download = filename;

    // fix Firefox
    link.style.display = 'none';
    body.appendChild(link);

    link.click();
    body.removeChild(link);

    window.URL.revokeObjectURL(link.href);
  }
}

</script>

<style scoped lang="scss">
.fileList {
  width: 100%;
  height: auto;
  margin-bottom: 10px;

  .oneFileBody {
    width: 100%;
    height: auto;
    box-sizing: border-box;
    padding:0 10px;
    display: flex;
    align-items: center;
    display: -moz-flex;
    display: -webkit-flex;
    background-color: #eeeeee;
    position: relative;
  }

  .delBtn {
    color: red;
    cursor: pointer;
    margin-right: 10px;
  }

  .download {
    color: green;
    cursor: pointer;
    margin-right: 10px;
  }

  .oneFile {
    width: 250px;
    flex-basis: 250px;
    flex-shrink: 0;
    height: 30px;

    margin-bottom: 10px;
    line-height: 30px;
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis;

    .fileName {
      width: 100%;
      margin:0 10px;
      height: auto;
      overflow:hidden;
      white-space:nowrap;
      text-overflow:ellipsis;
    }
  }
}
</style>
